using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;

namespace Attach.Internal
{
    public class Behaviors
    {
        private Dictionary<string, List<IBehavior>> behaviors = new Dictionary<string, List<IBehavior>>();
        private Dictionary<MethodInfo, bool> methodInfoBehaviors = new Dictionary<MethodInfo, bool>();

        public ContinueMethod GetBehaviorsMethod(string methodName, ContinueMethod targetMethod)
        {
            if (!behaviors.ContainsKey(methodName))
            {
                return targetMethod;
            }
            else
            {
                List<IBehavior> methodBehaviors = behaviors[methodName];
                methodBehaviors[methodBehaviors.Count - 1].Continue = targetMethod;
                return methodBehaviors[0].Run;
            }
        }

        public void Add(MethodInfo methodInfo, IBehavior behavior)
        {
            string methodName = methodInfo.Name;
            if (!behaviors.ContainsKey(methodName))
                behaviors[methodName] = new List<IBehavior>();

            List<IBehavior> methodBehaviors = behaviors[methodName];
            if (methodBehaviors.Count > 0)
                behaviors[methodName][behaviors[methodName].Count - 1].Continue = behavior.Run;

            behaviors[methodName].Add(behavior);
            methodInfoBehaviors[methodInfo] = true;
            if (behaviors.Count != methodInfoBehaviors.Count)
            {
                throw new Exception("Cannot add behavior to multiple overloads");
            }
        }
    }
}
